package com.chs.recoginition.core.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.chs.recoginition.core.exception.ApplicationException;
import com.chs.recoginition.core.exception.constant.ExceptionConstant;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonUtils {

    /**
     * 转为json字符串
     */
    public static String toJson(Object o) {
        try {
            ObjectMapper objectMapper = getObjectMapper();
            return objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
            throw new ApplicationException(ExceptionConstant.STR_FORMAT_FAIL, "json格式化失败");
        }
    }

    /**
     * json 转对象
     */
    public static <T> T parse(String jsonStr, Class<T> clazz) {
        return parse(objectMapper -> objectMapper.readValue(jsonStr, clazz));
    }

    /**
     * json 转对象
     */
    public static <T> T parseByType(String jsonStr, TypeReference typeReference) {
        return parse(objectMapper -> objectMapper.readValue(jsonStr, typeReference));
    }

    /**
     * json 转对象
     */
    public static <T> T parse(ThrowableFunction<ObjectMapper, T> function) {
        try {
            ObjectMapper objectMapper = getObjectMapper();
            return function.apply(objectMapper);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ApplicationException(ExceptionConstant.STR_FORMAT_FAIL, "json格式化失败");
        }
    }

    private static ObjectMapper getObjectMapper() {
        ObjectMapper objectMapper = SpringContextUtils.getBean(ObjectMapper.class);
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
            objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            objectMapper.registerModule(new JavaTimeModule());
        }
        return objectMapper;
    }

    @FunctionalInterface
    public interface ThrowableFunction<T, R> {

        R apply(T t) throws Exception;
    }
}
